import { Provide, Config, Plugin} from '@midwayjs/decorator';

import { IWebMiddleware, IMidwayWebNext } from '@midwayjs/web';
import { Context } from 'egg';
import { BaseController } from '../controller/base';

@Provide()
export class JwtAuthMiddleware extends BaseController implements IWebMiddleware {
  @Config('jwt')
  jwtConfig;
  @Plugin()
  jwt: any;
   // 验证token
   checkToken(token: string) {
    return this.jwt.verify(token, this.jwtConfig.secret);
  }
  resolve() {
    return async (ctx: Context, next: IMidwayWebNext) => {
      const path = ctx.path
      // admin 接口开启jwt验证
      if(path.startsWith('/admin/')) {
        const api = ctx.path.replace(/^\/admin/, '')
        // 登录接口不做验证
        if(api === '/login') {
          await next();
          return
        }
  
        const header = ctx.request.header
        if(!header['x-token']) {
          return ctx.body = this.errorResponse(this.ERROR_CODE_TOKEN_EMPTY)
        }
        const token = header['x-token'] as string
        if(!this.checkToken(token)) {
          return ctx.body = this.errorResponse(this.ERROR_CODE_TOKEN_ERROR)
        }
        await next();
        return
      }
      await next();
    };
  }
}
